<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    #drawing {
      border: 10px solid #ccc;
    }
  </style>
</head>
<body>
  <img src="./cat.jpg" alt="">
  <canvas id="drawing" width="200" height="200"></canvas>

  <script>
    let drawing = document.getElementById("drawing");
    
    // 确保浏览器支持<canvas>
      if (drawing.getContext) {
        let context = drawing.getContext("2d"),
        image = document.images[0],
        imageData, data,
        i, len, average,
        red, green, blue, alpha;
        
        // 绘制图像
        context.drawImage(image, 0, 0);
        
        // 取得图像数据
        // 因为图片资源存储在本地时默认没有域名，所以使用 getImageData 处理本地图片时浏览器会判定跨域而报错，canvas 只能绘制同域内容
        imageData = context.getImageData(0, 0, image.width, image.height);
        data = imageData.data;

      for (i=0, len=data.length; i < len; i+=4) {
        red = data[i];
        green = data[i+1];
        blue = data[i+2];
        alpha = data[i+3];

        // 取得RGB平均值
        average = Math.floor((red + green + blue) / 3);

        // 设置颜色，不管透明度
        data[i] = average;
        data[i+1] = average;
        data[i+2] = average;
      }

      // 将修改后的数据写回 ImageData
      imageData.data = data;
      // 应用到画布上显示出来
      context.putImageData(imageData, 0, 0);
    }
  </script>
</body>
</html>